﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmallERP.MODEL;
using SmallERP.DAL;
using SmallERP.Bll.Com;
using SmallERP.MODEL.FoundationModel;
using SmallERP.MODEL.MakeBigPic;
using System.Data;
using System.Data.OleDb;

namespace SmallERP.Bll.MakeBigPic
{
    /// <summary>
    /// 关于大板的各种处理类
    /// </summary>
    public class BoardBLL
    {
        public string addr { get; set; }
        public int port { get; set; }
        private string _dogCode;


        private string GetDogCode()
        {
            if (string.IsNullOrEmpty(_dogCode))
            {
                _dogCode = UnityMethod.GetDogCode(addr, port);
            }

            return _dogCode;
        }

        /// <summary>
        /// 更新大板
        /// </summary>
        /// <param name="upBoard"></param>
        public static void UpdateBoard(int boardId, int boardStatus, string remark)
        {
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    Board curB = db.Board.FirstOrDefault(b => b.BoardId == boardId);
            //    if (curB != null)
            //    {
            //        curB.LastPrintTime = UnityMethod.GetSystemTime();
            //        curB.Status = boardStatus;
            //        curB.Remark = remark;
            //    }
            //    db.SaveChanges();
            //}

            string UpdateBoard = "update board set LastPrintTime='" + DateTime.Now + "',Status=" + boardStatus + ",Remark='" + remark + "' where boardid=" + boardId;
            int a = SmallERP.DAL.AccessHelper.ExecuteNonQuery(UpdateBoard);

        }

        /// <summary>
        /// 从数据库中得到一个可用来生成大图的板
        /// </summary>
        /// <returns></returns>
        public BoardInfo_MakeBigPic GetOneBoardToProduct()
        {
            BoardInfo_MakeBigPic resultBoard = new BoardInfo_MakeBigPic();
            int waitProductStatus = (int)SmallERP.COM.Status.EnumBoardStatus.waitProduct;
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    Board curb = db.Board.Where(b => b.Status == waitProductStatus).OrderByDescending(b => b.PrintPriority).ThenBy(b => b.CreateTime).FirstOrDefault();
            //    if (curb != null)
            //    {
            //        #region base info
            //        if (!curb.PaperTypeReference.IsLoaded)
            //        {
            //            curb.PaperTypeReference.Load();
            //        }

            //        PrinterSeting printerSetting = db.PrinterSeting.FirstOrDefault(ps => ps.PrinterId == curb.PrinterId && ps.PaperTypeId == curb.PaperType.PaperTypeId);
            //        if (printerSetting != null)
            //        {
            //            resultBoard.AddSharpen = printerSetting.Sharpening;
            //            resultBoard.IccPath = printerSetting.ICCPATH;
            //        }
            //        else
            //        {
            //            resultBoard.AddSharpen = 0;
            //            resultBoard.IccPath = @"\\";
            //        }
            //        printer curp = db.printer.FirstOrDefault(p => p.PrinterID == curb.PrinterId);
            //        if (curp != null)
            //        {
            //            resultBoard.IsTransverse = curp.IsTransverse;
            //        }
            //        else
            //        {
            //            resultBoard.IsTransverse = false;
            //        }


            //        resultBoard.BoardBaseInfo = new Board_Info()
            //        {
            //            BoardId = curb.BoardId,
            //            CreateTime = curb.CreateTime,
            //            DPI = curb.DPI,
            //            Height = curb.Height,
            //            LastPrintTime = curb.LastPrintTime,
            //            Length = curb.Length,
            //            PrinterId = curb.PrinterId,
            //            PrintNum = curb.PrintNum,
            //            Remark = curb.Remark,
            //            Status = curb.Status,
            //            PrintPriority = curb.PrintPriority,
            //            WasteRate = curb.WasteRate,
            //            PicPath=curb.picPath
            //        };
            //        #endregion

            //        #region photoInfo

            //        resultBoard.PhotoS = new List<PhotoInfo_MakeBigPic>();
            //        if (!curb.PicMakeUp.IsLoaded)
            //        {
            //            curb.PicMakeUp.Load();
            //        }
            //        foreach (var pm in curb.PicMakeUp.ToList())
            //        {
            //            if (!pm.photoInfoReference.IsLoaded)
            //            {
            //                pm.photoInfoReference.Load();
            //            }
            //            if (!pm.photoInfo.orderInfoReference.IsLoaded)
            //            {
            //                pm.photoInfo.orderInfoReference.Load();
            //            }

            //            PhotoInfo_MakeBigPic pm_makeBigPic = new PhotoInfo_MakeBigPic()
            //            {
            //                PmID=pm.ID,
            //                //X = EncryptPoint(pm.X),
            //                //Y = EncryptPoint(pm.Y),
            //                Location = new System.Drawing.Point(0, 0),
            //                IsWhirl = pm.IsWhirl,
            //                barCodeStatus = (SmallERP.COM.Status.PhotoBarCodeStatus)pm.BarCodeStatus,
            //                Priority = pm.photoInfo.orderInfo.Priority,
            //                OrderProductName = pm.photoInfo.orderInfo.OrderName
            //            };

            //            pm_makeBigPic.BasePhotoInfo = new Photo_Info()
            //            {
            //                Height = pm.photoInfo.Height,
            //                Width = pm.photoInfo.Width,
            //                IsClearBox = pm.photoInfo.IsClearBox,
            //                IsReback = pm.photoInfo.IsReback,
            //                OrderProductId = pm.photoInfo.orderInfo.OrderProductId,
            //                PhotoId = pm.photoInfo.PhotoId,
            //                PhotoName = pm.photoInfo.PhotoName,
            //                PicPath = pm.photoInfo.PicPath,
            //                PixHeight = Convert.ToInt32(pm.photoInfo.Height * curb.DPI),
            //                PixWidth = Convert.ToInt32(pm.photoInfo.Width * curb.DPI),
            //                Remark = pm.photoInfo.Remark,
            //                Status = pm.photoInfo.Status,
            //                TotalNum = pm.photoInfo.TotalNum
            //            };
            //            ////try
            //            ////{
            //            ////    pm_makeBigPic.Location = new System.Drawing.Point(Convert.ToInt32(pm_makeBigPic.X), Convert.ToInt32(pm_makeBigPic.Y));
            //            ////}
            //            ////catch (Exception)
            //            ////{                            
            //            ////    throw new Exception("服务器加密狗信息错误！");
            //            ////}

            //            resultBoard.PhotoS.Add(pm_makeBigPic);
            //        }
            //        #endregion
            //    }
            //    else
            //    {
            //        return null;
            //    }
            //}

            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (var tran = oleconn.BeginTransaction())
            {

               

                string getBoardSql = "select  * from board where status=" + waitProductStatus + " order by PrintPriority desc,CreateTime";
                DataTable tableBoard = AccessHelper.dataTable(getBoardSql, oleconn,tran);
                if (tableBoard.Rows.Count <= 0)
                {
                    return null;
                }
                resultBoard.BoardBaseInfo = new Board_Info()
                {
                    AutoPoint = Convert.ToString(tableBoard.Rows[0]["AutoPoint"]),
                    BoardId = Convert.ToInt32(tableBoard.Rows[0]["BoardId"]),
                    CreateTime = Convert.ToDateTime(tableBoard.Rows[0]["CreateTime"]),
                    DPI = Convert.ToInt32(tableBoard.Rows[0]["DPI"]),
                    Height = Convert.ToInt32(tableBoard.Rows[0]["Height"]),
                    LastPrintTime = Convert.ToDateTime(tableBoard.Rows[0]["LastPrintTime"]),
                    Length = Convert.ToInt32(tableBoard.Rows[0]["Length"]),
                    PaperFaceId = Convert.ToInt32(tableBoard.Rows[0]["PaperFaceId"]),
                    PaperTypeId = Convert.ToInt32(tableBoard.Rows[0]["PaperTypeId"]),
                    PicPath = Convert.ToString(tableBoard.Rows[0]["PicPath"]),
                    PrinterId = Convert.ToInt32(tableBoard.Rows[0]["PrinterId"]),
                    PrintNum = Convert.ToInt32(tableBoard.Rows[0]["PrintNum"]),
                    PrintPaperId = Convert.ToInt32(tableBoard.Rows[0]["PrintPaperId"]),
                    PrintPriority = Convert.ToInt32(tableBoard.Rows[0]["PrintPriority"]),
                    Remark = Convert.ToString(tableBoard.Rows[0]["Remark"]),
                    Status = Convert.ToInt32(tableBoard.Rows[0]["status"]),
                    WasteRate = Convert.ToInt32(tableBoard.Rows[0]["WasteRate"])
                };
                string QueryPrinterSetting = "select * from PrinterSeting where printerid=" + resultBoard.BoardBaseInfo.PrinterId + " and papertypeid=" + resultBoard.BoardBaseInfo.PaperTypeId;
                DataTable tablePS = AccessHelper.dataTable(QueryPrinterSetting,oleconn, tran);
                if (tablePS.Rows.Count > 0)
                {
                    resultBoard.AddSharpen = Convert.ToInt32(tablePS.Rows[0]["AddSharpen"]);
                    resultBoard.IccPath = Convert.ToString(tablePS.Rows[0]["IccPath"]);
                }
                else
                {
                    resultBoard.AddSharpen = 0;
                    resultBoard.IccPath = @"\\";
                }
                string QueryPrinter = "select IsTransverse from printer where printerid=" + resultBoard.BoardBaseInfo.PrinterId;
                DataTable tablePrinter = AccessHelper.dataTable(QueryPrinter,oleconn, tran);
                resultBoard.IsTransverse = Convert.ToBoolean(tablePrinter.Rows[0]["IsTransverse"]);


                resultBoard.PhotoS = new List<PhotoInfo_MakeBigPic>();

                string QueryPicMakeup = "select id,BarCodeStatus,X,Y,orderinfo.Priority as Priority,OrderName,Height,IsClearBox,IsReback,Width,dpi,PixWidth,PixHeight,orderinfo.OrderProductId as OrderProductId ,photoinfo.PhotoId as PhotoId ,PhotoName "
                + ",photoinfo.PicPath as PicPath,photoinfo.Remark as Remark,photoinfo.Status as Status,photoinfo.TotalNum as TotalNum,IsWhirl from picmakeup,photoinfo,orderinfo where photoinfo.orderproductid=orderinfo.orderproductid and picmakeup.photoid=photoinfo.photoid and boardid= " + resultBoard.BoardBaseInfo.BoardId;
                DataTable tablePic = AccessHelper.dataTable(QueryPicMakeup, oleconn, tran);

                for (int i = 0; i < tablePic.Rows.Count; i++)
                {
                    PhotoInfo_MakeBigPic pm_makeBigPic = new PhotoInfo_MakeBigPic()
                    {
                        PmID = Convert.ToInt32(tablePic.Rows[i]["ID"]),
                        barCodeStatus = (SmallERP.COM.Status.PhotoBarCodeStatus)Convert.ToInt32(tablePic.Rows[i]["BarCodeStatus"]),
                        X = Convert.ToString(tablePic.Rows[i]["X"]),
                        Y = Convert.ToString(tablePic.Rows[i]["Y"]),
                        Priority = Convert.ToInt32(tablePic.Rows[i]["Priority"]),
                        OrderProductName = Convert.ToString(tablePic.Rows[i]["OrderName"]),
                        Location = new System.Drawing.Point(0, 0),
                        IsWhirl = Convert.ToBoolean(tablePic.Rows[i]["IsWhirl"])

                    };
                    int dpi = Convert.ToInt32(tablePic.Rows[i]["dpi"]);
                    pm_makeBigPic.BasePhotoInfo = new Photo_Info()
                    {
                        Height = Convert.ToInt32(tablePic.Rows[i]["Height"]),
                        IsClearBox = Convert.ToBoolean(tablePic.Rows[i]["IsClearBox"]),
                        IsReback = Convert.ToBoolean(tablePic.Rows[i]["IsReback"]),
                        Width = Convert.ToInt32(tablePic.Rows[i]["Width"]),
                        OrderProductId = Convert.ToInt32(tablePic.Rows[i]["OrderProductId"]),
                        PhotoId = Convert.ToInt32(tablePic.Rows[i]["PhotoId"]),
                        PhotoName = Convert.ToString(tablePic.Rows[i]["PhotoName"]),
                        PicPath = Convert.ToString(tablePic.Rows[i]["PicPath"]),
                        PixHeight = Convert.ToInt32(Convert.ToDecimal(tablePic.Rows[i]["PixHeight"])/dpi) * resultBoard.BoardBaseInfo.DPI,
                        PixWidth = Convert.ToInt32(Convert.ToDecimal(tablePic.Rows[i]["PixWidth"]) / dpi) * resultBoard.BoardBaseInfo.DPI,
                        Remark = Convert.ToString(tablePic.Rows[i]["Remark"]),
                        Status = Convert.ToInt32(tablePic.Rows[i]["status"]),
                        TotalNum = Convert.ToInt32(tablePic.Rows[i]["TotalNum"])
                    };



                    resultBoard.PhotoS.Add(pm_makeBigPic);



                }
            }
            AccessHelper.CloseMyConnection(oleconn);
            return resultBoard;
        }

        /// <summary>
        /// 解坐标X、Y
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public string EncryptPoint(string strInput)
        {
            if (string.IsNullOrEmpty(_dogCode))
            {
                try
                {
                    _dogCode = GetDogCode();
                }
                catch (Exception)
                {
                    return string.Empty;
                }

                if (string.IsNullOrEmpty(_dogCode))
                    return string.Empty;
            }
            string key = _dogCode.Substring(0, 8);//前八位为KEY
            string encryptDogCode = _dogCode.Substring(8);
            string dogKey = Decipher(encryptDogCode, key);

            return Decipher(strInput, dogKey);
        }

        const int MIN_ASC = 32;
        const int MAX_ASC = 126;
        const int NUM_ASC = 95;
        //解密
        public string Decipher(string strFromText, string key)
        {
            StringBuilder result = new StringBuilder();
            char[] random = key.ToCharArray();
            char[] from_text = strFromText.ToCharArray();
            char[] buf1 = new char[8];
            int offset;
            int str_len = 1;
            int i;
            int ch;

            str_len = from_text.Length;
            try
            {
                for (i = 0; i < str_len; i++)
                {
                    ch = (int)from_text[i];
                    if (ch >= MIN_ASC && ch <= MAX_ASC)
                    {
                        ch = ch - MIN_ASC;
                        offset = (NUM_ASC + 1) * random[i];
                        ch = (ch - offset) % NUM_ASC;
                        if (ch < 0)
                        {
                            ch = ch + NUM_ASC;
                        }
                        ch = ch + MIN_ASC;
                        buf1[i] = (char)ch;
                    }
                    else
                    {
                        buf1[i] = from_text[i];
                    }
                }
                foreach (var item in buf1)
                {
                    result.Append(item);
                }
            }
            catch (Exception)
            {
                result = new StringBuilder("");
            }

            return result.ToString();
        }

        /// <summary>
        /// 生成大图成功
        /// </summary>
        /// <param name="BoardId"></param>
        /// <returns></returns>
        internal int MakeBigPicSusscess(BoardInfo_MakeBigPic boardInfo)
        {
            int result = 0;
            ////改大板的状态以及照片的状态 
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    Board b = db.Board.FirstOrDefault(bT => bT.BoardId == boardInfo.BoardBaseInfo.BoardId);
            //    if (b != null)
            //    {
            //        b.picPath = boardInfo.BoardBaseInfo.PicPath;
            //        b.Status = (int)SmallERP.COM.Status.EnumBoardStatus.WaitingPrint;
            //    }
            //    foreach (var pi in boardInfo.PhotoS)
            //    {

            //        photoInfo p = db.photoInfo.FirstOrDefault(pt => pt.PhotoId == pi.BasePhotoInfo.PhotoId);
            //        if (p != null)
            //        {
            //            p.Status = (int)SmallERP.COM.Status.PhotoStatus.Producted;
            //        }
            //    }

            //    try
            //    {
            //        db.SaveChanges();
            //    }
            //    catch (Exception)
            //    {
            //        result = -2;
            //    }
            //}
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();

            using (var tran = oleconn.BeginTransaction())
            {
            string updateBoard = "update board set picPath='" + boardInfo.BoardBaseInfo.PicPath + ", Status=" + (int)SmallERP.COM.Status.EnumBoardStatus.WaitingPrint + " where boardid=" + boardInfo.BoardBaseInfo.BoardId;
            int boardReault = AccessHelper.ExecuteNonQuery(updateBoard,oleconn, tran);
            if (boardReault > 0)
            {
                string updatePhotoInfo = "update photoinfo set status=" + (int)SmallERP.COM.Status.PhotoStatus.Producted + "where photoid in(select photoid from picmakeup where boardid=" + boardInfo.BoardBaseInfo.BoardId + ")";
                int PhotoInfoResult = AccessHelper.ExecuteNonQuery(updatePhotoInfo,oleconn, tran);
                if (PhotoInfoResult > 0)
                {
                    result = 1;
                }
                else
                {
                    result = 0;
                }
            }
            else
            {
                result = 0;
            }
           

            }
            AccessHelper.CloseMyConnection(oleconn);
            return result;
        }
    }
}
